package com.excel.strategy;

import cn.afterturn.easypoi.excel.entity.result.ExcelVerifyHandlerResult;
import cn.afterturn.easypoi.handler.inter.IExcelVerifyHandler;
import com.excel.entity.BaseExcelData;
import lombok.SneakyThrows;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Objects;

/**
 * @author fh
 * @date : 2024/6/14 11:18
 **/
public class ClassExcelVerifyHandler implements IExcelVerifyHandler<BaseExcelData> {


    @Override
    @SneakyThrows
    public ExcelVerifyHandlerResult verifyHandler(BaseExcelData t) {
        ExcelVerifyHandlerResult result = new ExcelVerifyHandlerResult();
        if (!Objects.isNull(t)) {
            result.setSuccess(!checkFieldAllNull(t));
        }
        return result;
    }


    public static boolean checkFieldAllNull(BaseExcelData object) throws IllegalAccessException {
        for (Field f : object.getClass().getDeclaredFields()) {
            f.setAccessible(true);
            if (Modifier.isFinal(f.getModifiers()) && Modifier.isStatic(f.getModifiers())) {
                continue;
            }
            if (f.get(object) != null) {
                return false;
            }
            f.setAccessible(false);
        }
        //父类public属性
        for (Field f : object.getClass().getFields()) {
            f.setAccessible(true);
            if (Modifier.isFinal(f.getModifiers()) && Modifier.isStatic(f.getModifiers())) {
                continue;
            }
            if (f.get(object) != null) {
                return false;
            }
            f.setAccessible(false);
        }
        return true;
    }

}
